package com.tarena.luban.demo.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;

//@Component
public class MyFilterTwo implements GlobalFilter, Ordered {
    /**
     * 使用MyFilterTwo操作响应实现拦截逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("myFilterTwo 生效了");
        //1. 获取响应对象response
        ServerHttpResponse response = exchange.getResponse();
        //2. 准备好拦截输出的内容
        String responseMessage = "你的请求被拦截了";
        //3. 解决乱码问题 以前设置response头 contentType "
        HttpHeaders headers = response.getHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //4. 数据需要按照webflux要求格式包装
        DataBufferFactory dbf = response.bufferFactory();
        //5. 字符串变成字节放进流中输出
        byte[] bytes = responseMessage.getBytes(StandardCharsets.UTF_8);
        DataBuffer dataBuffer = dbf.wrap(bytes);
        //6. 输出称为response的响应数据
        Mono<DataBuffer> monoDatabuffer = Mono.fromSupplier(new Supplier<DataBuffer>() {
            @Override
            public DataBuffer get() {
                return dataBuffer;
            }
        });
        /*Mono<Void> mono = chain.filter(exchange);*/
        return response.writeWith(monoDatabuffer);
    }

    /**
     * 过滤器排序的方法
     * @return
     */
    @Override
    public int getOrder() {
        return -1000;
    }
}
